package org.jeecg.modules.api.controller;

import org.jeecg.modules.system.service.FtpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/api/ftp")
public class FtpController {

    @Autowired
    private FtpService ftpService;

    @GetMapping("/files/{filename:.+}")
    public ResponseEntity<ByteArrayResource> getFile(@PathVariable String filename) throws IOException {
        byte[] fileData = ftpService.downloadFile(filename);

        ByteArrayResource resource = new ByteArrayResource(fileData);

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .contentLength(fileData.length)
                .body(resource);
    }

    @PostMapping("/files")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        String filePath = file.getOriginalFilename(); // 你可以根据需要修改文件路径

        ftpService.uploadFile(filePath, file);

        return ResponseEntity.ok("File uploaded successfully");
    }
}
